<?php
/**
 * Created by PhpStorm.
 * User: askar
 * Date: 26.12.13
 * Time: 12:42
 */

class CategoryController extends Controller
{
	public $baseUrl;
	public $isCatalog;
	public $login;
	public $title, $categories;

	public function init() {
		$this->baseUrl = Yii::app()->request->baseUrl;
		$this->isCatalog = true;
		$session = new CHttpSession;
		$session->open();
		$this->login = $session['login'];
		//$this->layout = 'admin.views.layouts.main';
		$session->close();

		$this->title = 'Каталог';
		$this->categories = array(
			'index' => array('title' => 'Рестораны', 'url' => CHtml::normalizeUrl(array('catalog/'))),
			'actions' => array('title' => 'Акции', 'url' => CHtml::normalizeUrl(array('catalog/actions')))
		);
	}
	public static function loadModel($id=false, $ml=false) {
		if( $ml ) {
			if( $id ) {
				$model = Category::model()->multilang()->findByPk((int) $id);
			} else {
				$model = Category::model()->multilang();
			}
		} else {
			$model = Category::model()->findByPk((int) $id);
		}
		if ($model === null)
			throw new CHttpException(404, 'The requested post does not exist.');
		return $model;
	}
	public function actionIndex() {
		$this->categories['index']['active'] = true;
		$data['lists'] = Category::model()->findAll(array('order'=>'`main` DESC, `filter` DESC, `order` ASC'));
		$this->render('catalog', $data);
	}
	//region Управление категориями
	public function actionCreateCategory() {
		$data='';
		$data['cats'] = Category::model()->findAll( array('order'=>'`order` ASC') );
		$this->renderPartial('category',$data);
	}
	public function actionEditForm($id) {
		$data['cat'] = self::loadModel($id,true);
		$this->renderPartial('category_form', $data);
	}
	public function actionAddForm($parent_id) {
		$criteria = new CDbCriteria;
		$criteria->order = '`t`.`order` DESC';
		//$criteria->limit = 1;
		$criteria->condition = 'parent_id = :parent_id';
		$criteria->params = array(':parent_id'=>$parent_id);
		$category = Category::model()->multilang()->find($criteria);
		if( $category ) {
			$data['last_order'] = $category->order + 1;
		}
		//$data['cat'] = $category;
		$data['parent_id'] = $parent_id;
		echo '<pre>';
		print_r($data);
		echo '</pre>';
		$this->renderPartial('category_form', $data);
	}
	public function actionSaveCategory($id) {
		if( $id == 'new' ) {
			$record = new Category;
			//$record = $record->multilang();
		} else {
			$record = self::loadModel((int)$id,true);
		}
		$cat_record = Yii::app()->getRequest()->getPost('cat');

		$record->attributes = $cat_record;
		if( isset($cat_record['parent_id']) ) {
			$record->level = self::loadModel( (int) $cat_record['parent_id'] )->level + 1;
			$record->parent_id = (int) $cat_record['parent_id'];
		}
		if( $record->save() ) {
//			print_r('saved');
			$this->redirect(CHtml::normalizeUrl(array('catalog/')));
		} else {
			$file_path = YiiBase::getPathOfAlias('webroot').$cat_record['img'];
			if( file_exists( $file_path ) ) {
				unlink( $file_path );
			}
			print_r('save error');
		}
	}
	public function actionDeleteCategory($id) {
		$this->deleteCategoriesRecursive($id);
		$this->redirect(CHtml::normalizeUrl(array('catalog/')));
	}
	public function deleteCategoriesRecursive($id) {
		$category = Category::model()->findByPk( $id );
		if( file_exists( YiiBase::getPathOfAlias('webroot').$category->img ) ) {
			@unlink(YiiBase::getPathOfAlias('webroot').$category->img);
		}
		$level = $category->level;
		$parent_id = $category->id;
		$category->delete();
		if( $categories = $this->getChilds( $level,$parent_id ) ) {
			foreach ($categories as $category) {
				$category->delete();
			}
		}
	}
	public function getChilds($parent_level,$parent_id) {
		if( $parent_level < 3 ) {
			if( $categories = Category::model()->findAllByAttributes(array('level'=>$parent_level+1,'parent_id'=>$parent_id)) ) {
				if( $parent_level < 2 ) {
					foreach( $categories as $category ) {
						$categories = array_merge( $categories, $this->getChilds($category->level,$category->id) );
					}
				}
				return $categories;
			}
		}
		return array();
	}
	/*
	 * OLD
	 */
	public function uploadImage($file, $directory) {
		$date = date('YmdHis');
		$i = rand(1, 100000);
		$ext = end(explode(".", $file['name']));
		move_uploaded_file($file['tmp_name'],
			YiiBase::getPathOfAlias('webroot') . "/userfiles/".$directory."/x" . $i .'d'.$date . '.' . $ext);
		return "/userfiles/".$directory."/x" . $i .'d'.$date . '.' . $ext;
	}
	public function actionUploadIcon() {
		foreach ($_FILES as $file) {
			if($file['tmp_name']) {
				echo $this->uploadImage($file, $_GET['f']);
			}
		}
	}
	public function actionUpdateCategoryOrder() {
		$record = Category::model()->findByPk($_GET['id']);
		$record->order = $_GET['order'];
		$record->save();
	}
}